<?php
namespace app\admin\module;

use app\admin\util\Aes;
use app\admin\util\Token;
use app\common\model\Admin;
use think\Exception;
use think\facade\Cache;

/**
 * 因为服务的名字已经被系统用去了，为了不冲突，还是用module吧
 * Class LoginModule
 * @package app\admin\module
 */
class LoginModule{

    public static function login($username,$password){

        $user = Admin::where(['username'=>$username,'password'=>Token::password($password)])->find();
        if(empty($user)){
            throw new Exception("用户名或者密码错误");
        }

        //保存用户信息
        $key = "user_admin_info:".$user['id'];
        $redis = Cache::store("redis");
        $redis->hMSet($key, $user->toArray());

        //用户目录
        if($user['is_super']){
            $menu = PermissionModule::getAllMenu();
            $permissions = PermissionModule::getAllPermission();
        }else{
            $menu = PermissionModule::getMenu($user['role_id']);
            $permissions = PermissionModule::getPermission($user['role_id']);
        }

        $top = [];
        foreach($menu  as $key=>$item){
            if($item['pid']==0){
                array_push($top,$item);
                unset($menu[$key]);
            }
        }
        foreach($top as $key=> $item){
            if(!isset($item['sub'])){
                $top[$key]['sub'] = [];
            }
            foreach($menu as $sk => $sv){
                if($sv['pid'] == $item['id']){
                    array_push($top[$key]['sub'],$sv);
                    unset($menu[$sk]);
                }
            }
        }
        $menuKey = "user_admin_menu:".$user['id'];
        $permissionKey = "user_admin_permission:".$user['id'];
        $redis->set($menuKey,json_encode($top));
        //用户权限
        $redis->set($permissionKey,json_encode($permissions));

        //生成token
        $aes = new Aes();
        return $aes ->setToken($user['id']);
    }

    public static function logout($uid){
        $redis = Cache::store("redis");
        $redis->del("user_admin_menu:".$uid);
        $redis->del("user_admin_permission:".$uid);
        $redis->del("user_admin_info:".$uid);
    }


    public static function info($uid){
        $redis = Cache::store('redis');
        return $redis->hGetAll("user_admin_info:".$uid);
    }

    public static function menu($uid){
        $redis = Cache::store('redis');
        $menu = $redis->get("user_admin_menu:".$uid);
        return json_decode($menu,true);
    }

    public static function permission($uid){
        $redis = Cache::store('redis');
        $permission = $redis->get("user_admin_permission:".$uid);
        return json_decode($permission,true);
    }
}